package com.demo.cms.action.manage;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.demo.core.dao.base.support.ResultSearchResult;
import com.demo.core.dao.base.support.SearchArgumentSupport;
import com.demo.core.model.MemberRole;
import com.demo.core.model.Role;
import com.demo.core.model.Site;
import com.demo.core.model.Member;
import com.demo.core.model.User;
import com.demo.core.service.base.MemberRoleService;
import com.demo.core.service.base.MemberService;
import com.demo.core.service.base.RoleService;
import com.demo.core.service.base.UserService;
import com.demo.core.service.exception.MemberAlreadyExistedException;
import com.demo.security.access.model.SecurityUser;
import com.demo.security.annotation.function.Function;
import com.demo.webapp.action.PageAction;
import com.demo.webapp.context.MultisiteContextHolder;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;

/**
 * 会员管理ACTION
 * 包含会员管理和会员角色管理
 * @author ryuu.kk
 *
 */
@Function(id = 100700, pid = 10, code = "manage.member", name="会员管理")
public class MemberAction extends PageAction {

	/**
	 * 版本序列化ID
	 */
	private static final long serialVersionUID = -3177024237059483550L;
	
	/**
	 * 会员ID
	 */
	private Long id;
	
	/**
	 * 会员模型
	 */
	private Member member;
	
	/**
	 * 会员角色模型
	 */
	private MemberRole memberRole;
	
	/**
	 * 会员模型列表
	 */
	private List<Member> memberList;
	
	/**
	 * 用户模型列表
	 */
	private List<User> userList;
	
	/**
	 * 角色模型列表
	 */
	private List<Role> roleList;
	
	/**
	 * 会员角色模型
	 */
	private List<MemberRole> memberRoleList;
	/**
	 * 会员服务
	 */
	private MemberService memberService;
	
	/**
	 * 用户服务
	 */
	private UserService userService;
	
	/**
	 * 会员角色服务
	 */
	private MemberRoleService memberRoleService;

	/**
	 * 角色服务
	 */
	private RoleService roleService;
	
	/**
	 * 会员一览
	 * @return
	 */
	@Function(id = 100710, pid = 100700, code = "manage.member.list")
	public String list() {
		// 取得站点ID
		Site site = MultisiteContextHolder.getSite();
		Long siteId = site.getId();
		// 取得分页参数模型
		SearchArgumentSupport args = getArgumentSupport();
		//ResultSearchResult<Member> result = memberService.searchUnion(siteId, "", args.getFirstResult(), args.getMaxResults());
		ResultSearchResult<Member> result = memberService.searchUnion(siteId, args);
		this.setResultSupport(result);
		//memberList = new ArrayList<Member>(result.getResults());
		memberList = new ArrayList<Member>(result.getResults());
		return SUCCESS;
	}
	
	/**
	 * 会员创建画面
	 * @return String
	 */
	@Function(id = 100720, pid = 100700, code = "manage.member.create")
	public String create() {
		
		// 取得分页参数模型
		SearchArgumentSupport args = getArgumentSupport();
		// 取得所有用户
		ResultSearchResult<User> result = userService.search("", args.getFirstResult(), Integer.MAX_VALUE);
		this.setResultSupport(result);
		userList = new ArrayList<User>(result.getResults());
		return SUCCESS;
	}
	
	/**
	 * 创建频道信息
	 * @return String
	 */
	@Function(id = 100730, pid = 100700, code = "manage.member.save")
	//@InputConfig(resultName=CALLBACK) // 验证错误重定向到输入页
	@InputConfig(methodName="create", resultName="input") // 验证错误转向Member_save-input错误页
	public String save() {
		// 设置站点
		Long siteId = getSite().getId();
		member.setSiteId(siteId);
		// 账户可用
		member.setEnabled(true);
		// 账户未锁
		member.setLocked(false);
		// 账户有效
		member.setIsValid(true);
		// 密码盐值
		member.setRegisterTime(new Date());
		// 使用用户名对用户检索
		SecurityUser user = this.userService.find(member.getUser().getUserName());
		if (user == null) {
			// 存在用户找不到的错误
			LOG.error("Member save error, not found user in Member");
			addActionError(getText("user.notfound"));
			// 初始化用户列表
			create();
			return INPUT;
		}
		// 设置用户ID
		member.setUserId(user.getId());
		try {
			id = memberService.save(member);
		} catch (MemberAlreadyExistedException e) {
			addActionError(getText(e.getI18n()));
			// 初始化用户列表
			create();
			return INPUT;
		}
		addActionMessage(getText("member.added", "", member.getNickName()));
		return CALLBACK;
	}
	
	/**
	 * 会员编辑画面
	 * @return String 
	 */
	@Function(id = 100740, pid = 100700, code = "manage.member.edit")
	public String edit() {
		// 取得站点ID
		Site site = MultisiteContextHolder.getSite();
		Long siteId = site.getId();
		// 使用会员ID查找会员信息（只取得授予的角色并且已会员id进行分组）
		this.member = memberService.query(id);

		// 通过会员ID查询会员权限信息
		this.memberRoleList = memberRoleService.findRole(id);
		// 查找机构
		
		// 查找角色
		roleList = roleService.findList(siteId);
		
		return SUCCESS;
	}
	
	/**
	 * 会员更新画面
	 * 更新分为：
	 * 1.昵称更新
	 * 2.标志位更新
	 * 3.会员角色更新
	 * @return String
	 */
	@Function(id = 100750, pid = 100700, code = "manage.member.update")
	public String update() {
		// 更新会员信息
		memberService.updateNickName(id, member.getNickName());
		// 更新可用标志
		if (member.isEnabled() == null) {
			member.setEnabled(false);
		}
		enabled();
		
		// 更新锁定标志
		if (member.isLocked() == null) {
			member.setLocked(false);
		}
		locked();
		
		// 更新有效标志
		if (member.getIsValid() == null) {
			member.setIsValid(false);
		}
		isvalid();
		// 更新会员角色
		if (memberRoleList != null) {
			// 删除会员角色
			memberRoleService.deleteAll(id);
			for (MemberRole memberRole : memberRoleList) {
				memberRole.setStatus("RWD");
				memberRole.setModifyDate(new Date());
				memberRole.setMemberId(id);
				// 重新分配会员角色
				memberRoleService.save(memberRole);
			}
		}
		addActionMessage(getText("member.updated", "", member.getNickName()));
		return CALLBACK;
	}
	
	/**
	 * 删除会员信息
	 * @return String
	 */
	@Function(id = 100760, pid = 100700, code = "manage.member.delete")
	public String delete() {
		memberService.delete(id);
		return CALLBACK;
	}
	
	/**
	 * 会员可用
	 * @return String
	 */
	@Function(id = 100741, pid = 100740, code = "manage.member.edit.enabled")
	public String enabled() {
		memberService.enable(id, member.isEnabled());
		return CALLBACK;
	}
	
	/**
	 * 会员锁定
	 * @return String 
	 */
	@Function(id = 100742, pid = 100740, code = "manage.member.edit.locked")
	public String locked() {
		memberService.lock(id, member.isLocked());
		return CALLBACK;
	}
	
	/**
	 * 会员有效
	 * @return String
	 */
	@Function(id = 100743, pid = 100740, code = "manage.member.edit.isvalid")
	public String isvalid() {
		memberService.isValid(id, member.getIsValid());
		return CALLBACK;
	}
	
	/**
	 * 会员有效期限日
	 * @return String
	 */
	@Function(id = 100744, pid = 100740, code = "manage.member.edit.expireday")
	public String expireday() {
		memberService.expireDay(id, member.getExpireDay());
		return CALLBACK;
	}
	
	/**
	 * 批量删除会员信息
	 * @return String
	 */
	@Function(id = 100770, pid = 100700, code = "manage.member.edit.expireday")
	public String rm() {
		// 批量删除
		if (memberList != null) {
			for (Member member : memberList) {
				memberService.delete(member.getId());
			}
		}
		addActionMessage("会员信息已经成功删除.");
		return CALLBACK;
	}
	
	// ~~ settings here ------------------------------------------------------------
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Member getMember() {
		return member;
	}

	public void setMember(Member member) {
		this.member = member;
	}

	public MemberRole getMemberRole() {
		return memberRole;
	}

	public void setMemberRole(MemberRole memberRole) {
		this.memberRole = memberRole;
	}

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

	public List<Role> getRoleList() {
		return roleList;
	}

	public void setRoleList(List<Role> roleList) {
		this.roleList = roleList;
	}

	public List<Member> getMemberList() {
		return memberList;
	}

	public void setMemberList(List<Member> memberList) {
		this.memberList = memberList;
	}

	public List<MemberRole> getMemberRoleList() {
		return memberRoleList;
	}

	public void setMemberRoleList(List<MemberRole> memberRoleList) {
		this.memberRoleList = memberRoleList;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public void setMemberRoleService(MemberRoleService memberRoleService) {
		this.memberRoleService = memberRoleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}
}
